<template>
  <div>
    <a-layout style="min-height: 100vh;">
      <a-layout-sider v-model:collapsed="collapsed" collapsible theme="light">
        <div class="logo"><img src="../assets/guanli.png" alt="Logo" style="height: 100%; width: 200px"/></div>


        <a-menu
            v-model:selectedKeys="selectedKeys"
            v-for="menu in menuList"
            theme="light"
            mode="inline"
        >
          <a-menu-item :key="menu.parent.id" v-if="menu.children == null">
            <component class="icons" :is="dynamicIcon(menu.parent.icon)"></component>
            <span><router-link :to="menu.parent.url" class="link-color">{{ menu.parent.title }}</router-link></span>
          </a-menu-item>
          <a-sub-menu :key="menu.parent.id" v-if="menu.children != null">
            <template #title>
              <span>
                <component class="icons" :is="dynamicIcon(menu.parent.icon)"></component>
                <span>{{ menu.parent.title }}</span>
              </span>
            </template>
            <a-menu-item :key="child.id" v-for="child in menu.children">
              <router-link :to="child.url" class="link-color">{{ child.title }}</router-link>
            </a-menu-item>
          </a-sub-menu>

        </a-menu>
      </a-layout-sider>
      <a-layout>
        <a-layout-header style="background: #fff; text-align: right; padding-right: 20px;">
          <a-badge dot>
            <a href="">更新通知</a>
          </a-badge>
          &nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;
          <a-avatar :src="user.userimg" :size="50"/>&nbsp;
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              {{ user.name }}
              <DownOutlined/>
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="showDrawerImg">
                  <a href="#">修改头像</a>
                </a-menu-item>
                <a-menu-item @click="showDrawer">
                  <a href="#">修改密码</a>
                </a-menu-item>
                <a-menu-item @click="loginOut">
                  <a href="#">注销登录</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>

        </a-layout-header>
        <a-layout-content style="margin: 20px 16px">
          <div :style="{ padding: '25px', background: '#fff', minHeight: '810px' }">
            <router-view></router-view>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>


  <!--  更新密码-->
  <a-drawer
      title="更新密码"
      :width="720"
      :open="open"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
  >
    <a-form :model="form" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="旧密码" name="passwd">
            <a-input v-model:value="form.passwd" placeholder="请输入旧密码"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="新密码" name="newPassword">
            <a-input
                v-model:value="form.newPassword"
                style="width: 100%"
                placeholder="请输入新密码"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onChange">确认</a-button>
      </a-space>
    </template>
  </a-drawer>

  <!--  更新头像-->
  <a-drawer
      title="更新头像"
      :width="720"
      :open="open2"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose2"
  >
    <a-form :model="formImg" layout="vertical">
      <a-row :gutter="16">
        <a-upload
            v-model:file-list="fileList"
            :action="action"
            list-type="picture-card"
            @preview="handlePreview"
            @change="handleChange"
        >
          <div v-if="fileList.length < 1">
            <PlusOutlined/>
            <div style="margin-top: 8px">Upload</div>
          </div>
        </a-upload>
        <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage"/>
        </a-modal>
      </a-row>
    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="onClose2">取消</a-button>
        <a-button type="primary" @click="onChangeImg">确认</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
<script setup>
import {createVNode, h, onMounted, ref} from 'vue';
import {
  PieChartOutlined,
  DesktopOutlined,
  UserOutlined,
  PlusOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
  AreaChartOutlined
} from '@ant-design/icons-vue'
import {Modal, notification} from "ant-design-vue";
import ajax from "@/main"
import {BaseUrl} from "@/api.js";
import {useRouter} from 'vue-router';
import headImageSrc from '@/assets/images/head.png'


const iconMap = {
  'PieChartOutlined': PieChartOutlined,
  'UserOutlined': UserOutlined,
  'DesktopOutlined': DesktopOutlined
  // ... 其他图标
};

function dynamicIcon(iconName) {
  // 使用图标映射表来获取对应的图标组件
  return iconMap[iconName] || 'default-fallback-icon';
}

const router = useRouter();

const collapsed = ref(false);
const selectedKeys = ref([]);
const openKeys = ref([]);

const user = ref({
  id: '',
  name: '',
  userimg: '',
  userImgList: []
})

const form = ref({
  'id': '',
  'passwd': '',
  'newPassword': ''
})
const showConfirm = () => {
  Modal.confirm({
    title: '是否要注销登录?',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        '注销后将需要重新登录才能访问',
    ),
    onOk() {
      ajax.post('/demo/userChange/logOut', {'id': localStorage.getItem('id')}).then(res => {
            if (res.data.code === 200) {
              localStorage.removeItem('id')
              localStorage.removeItem('token')
              router.push('/login');
            } else {
              notification['error']({
                message: '注销失败',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
};

const open = ref(false);
const open2 = ref(false);
const showDrawer = () => {
  open.value = true;
};
const onClose = () => {
  open.value = false;
};

const onClose2 = () => {
  open2.value = false;
};

function onChange() {
  if (form.value.passwd && form.value.newPassword) {
    form.value.id = localStorage.getItem('id')
    ajax.post('/demo/userChange/changePasswd', form.value).then(res => {
      if (res.data.code === 200) {
        open.value = false;
        localStorage.setItem('tmpPass', form.value.passwd)
        form.value.passwd = ''
        form.value.newPassword = ''
      } else {
        notification['error']({
          message: '错误提示',
          description: res.data.msg,
        });
      }
    })
  } else {
    notification['error']({
      message: '错误提示',
      description: '未输入密码',
    });
  }
}

function loginOut() {
  showConfirm()
}

const headImg = ref(headImageSrc);

function showDrawerImg() {
  open2.value = true;
}

const fileList = ref([])

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

const action = BaseUrl + '/demo/userChange/changeImg'

const formImg = ref({
  'imgUrl': ''
})

function onChangeImg() {
  ajax.post('/demo/userChange/subChangeImg', user.value).then(res => {
    if (res.data.code === 200) {
      getUser();
      fileList.value = [];
      open2.value = false;
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })
}

function handleChange(file, fileList, event) {
  if (file.file.status === 'done') {
    user.value.userImgList = file.file.response.data
  }

}

function getUser() {
  ajax.get('/demo/userChange/getUser?id=' + localStorage.getItem('id')).then(res => {
    if (res.data.code === 200) {
      user.value = res.data.data
      user.value.userimg = BaseUrl + '/demo/images/' + res.data.data.userimg
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })
}

function getMenu() {
  ajax.get('/demo/userChange/getMenu?id=' + localStorage.getItem('id')).then(res => {
    if (res.data.code === 200) {
      menuList.value = res.data.data;
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  })
}

onMounted(() => {
  getUser();
  getMenu();
})

const menuList = ref([]);
</script>
<style scoped>
#components-layout-demo-side .logo {
  height: 32px;
  margin: 16px;
  background: rgba(255, 255, 255, 0.3);
}

.site-layout .site-layout-background {
  background: #fff;
}

[data-theme='dark'] .site-layout .site-layout-background {
  background: #141414;
}

.logo {
  width: 200px;
  height: 52px;
  margin-top: 5px;
  margin-bottom: 5px;
}

.link-color {
  text-decoration: inherit;
  color: inherit;
  width: 120px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

svg {
  width: 14px;
  height: 14px;
  margin-right: 5px;
  padding-top: -1px;
}

:deep(.ant-badge.ant-badge-status .ant-badge-status-dot) {
  width: 13px;
  height: 13px;
}

</style>